package com.zzg.lucene.search;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.springframework.util.StringUtils;

public class LuceneSearch {
	/**
	 * 创建索引读取器
	 *
	 * @param indexPath
	 * @param create
	 * @throws IOException
	 */
	public IndexSearcher  getIndexSearcher(String indexPath) throws IOException {
		Directory directory = null;
		//1、创建Directory 
		if(StringUtils.isEmpty(indexPath)){
			directory =  new RAMDirectory();
		} else{
			directory = FSDirectory.open(Paths.get(indexPath));
		}
		//2、创建IndexReader
		IndexReader reader = DirectoryReader.open(directory); 
		//3、根据IndexReader创建IndexSearcher 
		IndexSearcher indexSearcher = new IndexSearcher(reader); 
		return indexSearcher;
	}
	
	public void createSearch(String field, String keyword) throws IOException {
		IndexSearcher searcher = getIndexSearcher("C:\\lucene\\index");
		Query query = new TermQuery(new Term(field, keyword));
		TopDocs rs = searcher.search(query, 100);
        for (int i = 0; i < rs.scoreDocs.length; i++) {
            // rs.scoreDocs[i].doc 是获取索引中的标志位id, 从0开始记录
            Document firstHit = searcher.doc(rs.scoreDocs[i].doc);
            System.out.println("id:" + firstHit.getField("id").stringValue());
            System.out.println("country:" + firstHit.getField("country").stringValue());
            System.out.println("contents:" + firstHit.getField("contents").stringValue());
            System.out.println("city:" + firstHit.getField("city").stringValue());
        }
    }
	
	public static void main(String[] args) throws IOException{
		LuceneSearch search = new LuceneSearch();
		search.createSearch("country", "Italy");
	}
	
	

}
